<template>
  <!-- CouponSelectPosition 选择职务 -->
  <PageContainer>
    <view class="container">
      <Header title="选择职务" />
      <template v-for="v in dataList" :key="v.id">
        <view class="list-item" @click="itemClick(v)">
          <view class="checkbox">
            <image
              v-if="selectedFindIndex(v.id) !== -1"
              class="icon"
              src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/icon/card/selected-icon.png"
            />
            <image v-else class="icon" src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/icon/card/select-icon.png" />
          </view>
          <text class="level-name">{{ v.name }}</text>
          <text class="level-num">{{ v.count }}人</text>
        </view>
      </template>

      <TButtonGroup>
        <TButton class="gutter-btn" text="确认" custom-class="cardBtn" @click="onSubmit" />
      </TButtonGroup>
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /**  CouponSelectPosition  选择职务 */
  import PageContainer from '@/components/PageContainer/index.vue';
  import { getDownStatisticsList } from '@/api';
  import { type GetDownStatisticsListResult } from '@/api/indexTypes';
  import Header from '@/components/Header/index.vue';
  import { navigateBack, onLoad } from '@/router';
  import { type CouponSelectPosition } from '@/router/types/modules';
  import { ref } from 'vue';
  import TButtonGroup from '@/components/TButtonGroup/index.vue';
  import TButton from '@/components/TButtonGroup/TButton.vue';

  const selected = ref<GetDownStatisticsListResult[]>([]);
  let success: CouponSelectPosition['success'];

  const dataList = ref<GetDownStatisticsListResult[]>([]);

  getDownStatisticsList().then((r) => {
    dataList.value = r;
  });

  function itemClick(item: GetDownStatisticsListResult) {
    const index = selectedFindIndex(item.id);
    if (index !== -1) {
      selected.value.splice(index, 1);
    } else {
      selected.value.push(item);
    }
  }

  function selectedFindIndex(id: number) {
    return selected.value.findIndex((v) => v.id === id);
  }

  function customBack() {}

  function onSubmit() {
    success?.(selected.value);
    navigateBack();
  }

  onLoad<'CouponSelectPosition'>((op) => {
    selected.value = op.selected;
    success = op.success;
  });
</script>

<style lang="scss" scoped>
  .list-item {
    display: flex;
    align-items: center;
    height: 88rpx;
    background-color: #fff;
    margin-bottom: 2rpx;
    color: #333;
    font-size: 28rpx;
    .checkbox {
      flex-shrink: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 0 30rpx;
      .icon {
        width: 32rpx;
        height: 32rpx;
      }
    }
    .level-name {
      margin-right: 26rpx;
    }
  }
</style>
